<template>
  <div class="videoArea">
    <div class="areaLeft">
      <div class="areaInfo">
        <div class="areaInfoLeft">
          <div class="title">
            {{ courseData.name }}
            <div class="type">
              {{ courseData.parentCategoryName }} /
              {{ courseData.categoryName }}
            </div>
          </div>
          <div class="other">
            <div class="look">
              <img src="" alt="" srcset="" />
              {{ courseData.joins || 0 }}人学习
            </div>
            <div class="line"></div>
            <!-- <div class="status">已完结</div>
            <div class="line"></div> -->
            <div class="time">{{ formatDate(courseData.updateTime) }}</div>
          </div>
        </div>
        <CustomButton
          class="customBtn"
          type="primary"
          :icon="courseData.joined ? null : 'el-icon-plus'"
          :disabled="courseData.joined"
          @click="addLearn"
        >
          {{ courseData.joined ? (isPlayEnd ? '已完成' : '学习中') : '加入学习' }}
        </CustomButton>
      </div>
      <div class="areaPlay">
        <!-- <img
          v-if="!courseData.videoId"
          class="videoPlay"
          :src="$getImageUrl(courseData.originImg)"
        /> -->
        <!-- <video
          v-if="courseData.videoId"
          ref="videoPlayer"
          class="videoPlay"
          :poster="`${$basAssetsUrl}${courseData.originImg}`"
          controls
          controlslist="nodownload"
          @play="onPlay"
          @timeupdate="handleTimeUpdate"
          @loadedmetadata="onVideoLoaded"
          @ended="onVideoEnded"
        >
          <source
            :src="`${$basAssetsUrl}${courseData.videoId}`"
            type="video/mp4"
          />
        </video> -->
        <div id="videoPlayer" class="videoPlay"></div>
        <div class="option">
          <div class="optionLeft">
            <div class="optionItem" @click="setVoteCourseFn">
              <img
                v-if="!isVote"
                src="@/assets/like_icon.png"
                alt=""
                srcset=""
              />
              <img
                v-if="isVote"
                src="@/assets/like_select.png"
                alt=""
                srcset=""
              />
              <span>{{ likes }}</span>
            </div>
            <div class="optionItem" @click="setFavCourseFn">
              <img
                v-if="!isFav"
                src="@/assets/collect_icon.png"
                alt=""
                srcset=""
              />
              <img
                v-if="isFav"
                src="@/assets/collect_select.png"
                alt=""
                srcset=""
              />
            </div>
            <div class="optionItem">
              <el-popover
                placement="bottom-start"
                width="400"
                trigger="hover"
              >
                <div class="relayArea">
                  <el-input
                    ref="inputToCopy"
                    v-model="textToCopy"
                    readonly
                    placeholder="这里将显示要复制的文本"
                  ></el-input>
                  <el-button type="primary" @click="copyToClipboard">复制链接</el-button>
                </div>
                <img
                  src="@/assets/relay.png"
                  alt=""
                  srcset=""
                  slot="reference"
                />
              </el-popover>
            </div>
          </div>
          <!-- <div class="optionRgt">
            <img class="moreImg" src="@/assets/more.png" alt="" srcset="" />
          </div> -->
        </div>
      </div>
      <Introduce
        :description="courseData.description"
        :queryParams="queryParams"
      ></Introduce>
    </div>
    <div class="areaRgt">
      <div class="areaUser" v-if="expertData">
        <div class="userHead">
          <img
            :src="$getImageUrl(courseData.originImg)"
            alt=""
            srcset=""
          />
        </div>
        <div class="userInfo">
          <div class="name">{{ expertData.name }}</div>
          <div class="info">{{ expertData.title }}</div>
        </div>
      </div>
      <div class="areaDiscuss" v-if="topicData">
        <div class="title">所属专题</div>
        <div class="courseCard" @click="toTopic">
          <div class="cardBanner">
            <img
              class="cardImg"
              :src="$getImageUrl(topicData.originImg)"
              alt=""
              srcset=""
            />
            <!-- <div class="cardTag">
              <img src="" alt="" />
              16项目课程
            </div> -->
          </div>
          <div class="cardInfo">
            <div class="cardTitle moreHidden">
              {{ topicData.name }}
            </div>
            <div class="cardOther">
              <div class="lecturer">
                <img
                  class="calendarIcon"
                  src="@/assets/calendar-icon.png"
                  alt=""
                  srcset=""
                />
                {{ topicData.updateTime || '无' }}
              </div>
              <div class="booking">
                <img src="@/assets/users.png" alt="" />
                {{ topicData.joins || 0 }}人学习
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="relevantCourse" v-if="relatedCourses.length">
        <div class="title">相关课程</div>
        <div class="courseList">
          <div
            class="courseItem"
            v-for="(item, index) in relatedCourses"
            :key="'course' + index"
          >
            <div class="line" v-if="index !== 0"></div>
            <CourseCardHorizontal
              class="courseCardHorizontal"
              :cardData="item"
            ></CourseCardHorizontal>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken, getUserInfo } from '@/utils/auth'
import Introduce from './Introduce.vue';
import CustomButton from '@/components/CustomButton.vue';
import {
  getCourseDetails,
  getRelatedCourseTopic,
  voteCourse,
  getVoteStatusById,
  unVoteCourse,
  getFavStatusById,
  favCourse,
  unFavCourse,
  getLikesCountById,
  updateMyJoinedCourse,
  getLearnedByCourseId
} from '@/api/course';
import CourseCardHorizontal from '@/components/CourseCardHorizontal.vue';
import { joinCourse } from '@/api/personal'
import { copyToClipboard } from '@/utils'
import { toLogin } from '@/utils/baseConfig';

export default {
  name: 'PalyArea',
  components: { Introduce, CustomButton, CourseCardHorizontal },
  props: {
    queryParams: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      courseData: {}, // 课程详情
      relatedCourses: [], // 相关课程
      // 专题
      topicData: null,
      // 专家
      expertData: null,
      isVote: false,
      isFav: false,
      textToCopy: window.location.href,
      likes: 0, // 点赞数
      currentTime: 0, // 当前进度
      isPlayEnd: false, // 是否播放完成
      videoPlayer: null,
      player: null,
      siteId: null,
    };
  },
  computed: {
    isLogin() {
      return !!getToken();
    },
    userInfo() {
      return getUserInfo() || {}
    }
  },
	created() {
		this.setPlayerCallBack();
	},
  mounted() {
    console.log(this.userInfo.siteId, window.baseConfig.userId)
    this.siteId = this.userInfo.siteId || window.baseConfig.userId;
    if(this.siteId) {
      const script = document.createElement('script');
      script.src = `https://p.bokecc.com/player?siteid=${this.siteId}&newversion=true`;
      script.async = false; // 异步加载
      document.head.appendChild(script);
      script.onload = () => {
        console.log('脚本加载成功');
        this.initLoad();
      };
      script.onerror = () => {
        console.log('脚本加载失败');
        this.initLoad();
      };
    } else {
      return toLogin();
    }
  },
  beforeDestroy() {
    if(this.isLogin) {
      this.updateMyJoinedCourseFn();
    }
		this.player && this.player.destroy();
  },
  methods: {
    initLoad() {
      this.getData();
      this.getRelatedCourseTopicFn();
      this.getVoteStatusById();
      this.getFavStatusById();
      this.getLikesCountById()
    },
    // 创建视频
		createPlayer() {
			this.videoPlayer = document.getElementById("videoPlayer");
			this.player = window.createCCH5Player({
				vid: this.courseData.videoId,
				siteid: this.siteId,
				// autoStart: true,
				width: "100%",
				height: "100%",
				parentNode: this.videoPlayer,
			});
		},
    // 设置回调数据
		setPlayerCallBack() {
			window.onCCH5PlayerLoaded = this.onCCH5PlayerLoaded
			window.on_CCH5player_ready = this.onPlayerReady;
			window.on_player_volumechange = this.onPlayerVolumeChange;
			window.on_CCH5player_ended = this.onVideoEnded;
		},
		onCCH5PlayerLoaded() {
			window.ccH5PlayerJsLoaded = true;
		},
		onPlayerReady(obj) {
			console.log('CCH5player_ready', obj)
			window.cc_js_Player.setVolume(0.3);
      this.onVideoLoaded()
		},
		onPlayerVolumeChange(volume, vid) {
      console.log('设置音量回调:  ', volume, vid)
    },
    // 获取课程详情
    async getData() {
      try {
        let params = {
          objectId: this.queryParams.id,
        };
        const resData = await getCourseDetails(params);
        this.courseData = resData;
        this.isPlayEnd = resData.studyStatus === 'END';
        this.createPlayer();
      } catch (error) {
        console.error(error);
      }
    },
    // 获取相关课程和专题
    async getRelatedCourseTopicFn() {
      try {
        let params = {
          objectId: this.queryParams.id,
        };
        const resData = await getRelatedCourseTopic(params);
        this.expertData = resData.bizExpert;
        this.topicData =
          resData.bizTopics && resData.bizTopics.length
            ? resData.bizTopics[0]
            : null;
        this.relatedCourses = resData.relatedCourses || [];
      } catch (error) {
        console.error(error);
      }
    },

    // 获取点赞数
    async getLikesCountById() {
      try {
        let params = {
          courseId : this.queryParams.id,
        };
        const resData = await getLikesCountById(params);
        this.likes = resData;
      } catch (error) {
        console.error(error);
      }
    },
    
    // 获取是否已经点赞
    async getVoteStatusById() {
      try {
        let params = {
          courseId : this.queryParams.id,
        };
        const resData = await getVoteStatusById(params);
        this.isVote = resData;
      } catch (error) {
        console.error(error);
      }
    },
    // 课程点赞
    async setVoteCourseFn() {
      if(!this.isLogin) {
        return toLogin();
      }
      try {
        let params = {
          courseId : this.queryParams.id,
        };
        if(this.isVote) {
          await unVoteCourse(params);
          this.isVote = false;
          this.likes = this.likes - 1;
        } else {
          await voteCourse(params);
          this.isVote = true;
          this.likes = this.likes + 1;
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 获取是否已经收藏
    async getFavStatusById() {
      try {
        let params = {
          courseId : this.queryParams.id,
        };
        const resData = await getFavStatusById(params);
        this.isFav = resData;
      } catch (error) {
        console.error(error);
      }
    },

    // 课程收藏
    async setFavCourseFn() {
      if(!this.isLogin) {
        return toLogin();
      }
      try {
        let params = {
          courseId : this.queryParams.id,
        };
        if(this.isFav) {
          await unFavCourse(params);
          this.isFav = false;
        } else {
          await favCourse(params);
          this.isFav = true;
        }
      } catch (error) {
        console.error(error);
      }
    },

    // 加入学习
    async addLearn() {
      if(!this.isLogin) {
        return toLogin();
      }
      try {
        const params = {
          courseIds: [this.queryParams.id],
        };
        await joinCourse(params);
        this.getData();
      } catch (error) {
        console.error(error);
      }
    },
    // 时间格式化
    formatDate(value) {
      return this.$dayjs(value).format('YYYY年MM月DD日');
    },
    // 复制
    copyToClipboard() {
      copyToClipboard(this.textToCopy);
    },

    onPlay() {
      if(!this.isLogin) {
        return toLogin();
      }
    },

    // 视频播放进度
    handleTimeUpdate() {
      if (this.$refs.videoPlayer && this.currentTime !== Math.floor(this.$refs.videoPlayer.currentTime)) {
        this.currentTime = Math.floor(this.$refs.videoPlayer.currentTime);
      }
    },
    // 视频加载完成
    async onVideoLoaded() {
      // 禁止右键
      this.$nextTick(() => {
        document.querySelector('video').addEventListener('contextmenu', function(e) {
          e.preventDefault();
        });
      })
      if(this.isLogin) {
        try {
          let params = {
            courseId : this.queryParams.id,
          };
          const resData = await getLearnedByCourseId(params);
          this.currentTime = resData?.learnTimes || 0;
          window.cc_js_Player.jumpToTime(this.currentTime);
          // this.$refs.videoPlayer.currentTime = resData?.learnTimes || 0;
        } catch (error) {
          console.error(error);
        }
      }
    },

    // 更新播放进度
    async updateMyJoinedCourseFn() {
      this.currentTime = window.cc_js_Player.getPosition();
      try {
        let params = {
          courseId : this.queryParams.id,
          learnTimes: this.currentTime,
          status: this.isPlayEnd ? 'END' : 'START'
        };
        await updateMyJoinedCourse(params);
      } catch (error) {
        console.error(error);
      }
    },
    // 播放完成
    onVideoEnded() {
      this.isPlayEnd = true;
      this.updateMyJoinedCourseFn();
    },
    // 跳转到专题
    toTopic() {
      let params = {
        objectId: this.topicData.objectId,
      };
      this.$router.push({
        path: "/topic/detail",
        query: params,
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.videoArea {
  box-sizing: border-box;
  display: flex;
  justify-content: space-between;
  .areaLeft {
    width: 1026px;
    .areaInfo {
      width: 1026px;
      height: 109px;
      padding-top: 24px;
      box-sizing: border-box;
      display: flex;
      align-items: flex-start;
      justify-content: space-between;
      .areaInfoLeft {
        height: 100%;
      }
      .customBtn {
        padding: 10px 34px;
        margin-top: 10px;
      }

      .title {
        height: 28px;
        display: flex;
        align-items: center;
        color: $text-title-color;
        font-size: 20px;
        font-weight: 600;

        .type {
          font-size: 14px;
          font-weight: 600;
          line-height: 21px;
          color: $text-color;
          margin-left: 12px;
        }
      }
      .other {
        display: flex;
        align-items: center;
        margin-top: 8px;
        .look,
        .status,
        .time {
          font-size: 14px;
          font-weight: 400;
          color: $text-color;
        }
        .line {
          width: 1px;
          height: 12px;
          background-color: #c6c6c6;
          margin: 0 8px;
        }
      }
    }
    .areaPlay {
      width: 1026px;
      .videoPlay {
        width: 100%;
        height: 700px;
        display: block;
        object-fit: cover;
        background: #000;
      }
      .option {
        height: 68px;
        padding: 0 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: #fff;
        box-shadow: $box-shadow;
        border-radius: 0 0 8px 8px;
        .optionLeft {
          display: flex;
          align-items: center;
          .optionItem {
            display: flex;
            align-items: center;
            cursor: pointer;
            margin-right: 24px;
            font-size: 14px;
            font-weight: 400;
            span {
              width: 6px;
            }
            img {
              width: 28px;
              height: 28px;
              margin-right: 8px;
            }
          }
        }
        .optionRgt {
          .moreImg {
            width: 28px;
            height: 28px;
          }
        }
      }
    }
  }
  .areaRgt {
    width: 326px;
    margin-left: 24px;
    .title {
      font-size: 16px;
      font-weight: 600;
      line-height: 23px;
      color: $text-title-color;
      margin-bottom: 16px;
    }
    .areaUser {
      width: 100%;
      height: 109px;
      padding-top: 24px;
      box-sizing: border-box;
      display: flex;
      .userHead {
        width: 56px;
        height: 56px;
        border-radius: 50%;
        overflow: hidden;
        display: flex;
        align-items: center;
        img {
          width: 100%;
        }
      }
      .userInfo {
        margin-left: 12px;
        .name {
          font-size: 20px;
          font-weight: 600;
          line-height: 28px;
          color: $text-title-color;
        }
        .info {
          margin-top: 4px;
          font-size: 14px;
          font-weight: 400;
          line-height: 20px;
          color: $text-color;
        }
      }
    }

    .areaDiscuss {
      width: 100%;
      background: #fff;
      border-radius: 8px;
      box-shadow: $box-shadow;
      padding: 16px;
      box-sizing: border-box;

      .courseCard {
        width: 100%;
        border-radius: 8px;
        background: #fff;
        cursor: pointer;

        .cardBanner {
          width: 100%;
          height: 176px;
          position: relative;
          background: #fff;
          overflow: hidden;
          display: flex;
          align-items: center;
          border-radius: 8px;
          .cardImg {
            width: 100%;
            height: 176px;
            object-fit: cover;
          }
          .cardTag {
            color: #fff;
            padding: 4px 6px;
            border-radius: 2px 0px 0px 0px;
            background: rgba(0, 0, 0, 0.5);
            position: absolute;
            top: 8px;
            left: 8px;
            font-size: 12px;
            font-weight: 600;
            line-height: 17px;
          }
        }
        .cardInfo {
          padding: 12px 0 0;
          .cardTitle {
            width: 100%;
            height: 42px;
            font-size: 14px;
            font-weight: 600;
            line-height: 21px;
            color: $text-title-color;
            -webkit-line-clamp: 2;
          }
          .cardOther {
            display: flex;
            align-items: center;
            margin-top: 12px;
            justify-content: space-between;
            .lecturer {
              height: 18px;
              font-size: 12px;
              font-weight: 400;
              color: $text-color;
              display: flex;
              align-items: center;

              .calendarIcon {
                width: 12px;
                height: 12px;
                margin-left: 2px;
                margin-right: 6px;
              }
            }
            .booking {
              color: $text-color-secondary;
              font-size: 12px;
              font-weight: 400;
              line-height: 18px;
              display: flex;
              align-items: center;
              img {
                widows: 14px;
                height: 14px;
                margin-right: 4px;
              }
            }
          }
        }
      }
    }

    .relevantCourse {
      width: 100%;
      background: #fff;
      border-radius: 8px;
      box-shadow: $box-shadow;
      padding: 16px;
      box-sizing: border-box;
      margin-top: 24px;
      .courseList {
        width: 100%;
        .courseItem {
          width: 100%;
          .line {
            width: 100%;
            height: 1px;
            margin: 16px 0;
            background: #f0f0f0;
          }
          .courseCardHorizontal {
            width: 100%;
            height: 80px;
          }
        }
      }
    }
  }
}

.relayArea {
  display: flex;
  padding: 20px;
  box-sizing: border-box;
}
::v-deep .ccH5Poster img {
  width: 100%;
}
</style>
